﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace WcfServiceLibrary
{
    public sealed class SafeContainer
    {
        public static SafeContainer Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        class Nested
        {
            static Nested()
            {
            }

            internal static readonly SafeContainer instance = new SafeContainer();
        }

        private static readonly Dictionary<string, string> TokenDictionary = new Dictionary<string, string>();
        private static readonly Dictionary<string, DateTime> RequestDictionary = new Dictionary<string, DateTime>();

        private const int TIMEOUT = 2;
        static Timer _timer = new Timer(Clean, null, new TimeSpan(0, TIMEOUT, 0), new TimeSpan(0, TIMEOUT, 0));

        private static void Clean(object state)
        {
            lock (RequestDictionary)
            {
                foreach (var id in RequestDictionary.Keys)
                {
                    if (RequestDictionary[id].AddMinutes(TIMEOUT) < DateTime.Now)
                    {
                        RequestDictionary.Remove(id);
                    }
                }
            }
        }

        public bool AddRequestId(string requestId)
        {
            lock (RequestDictionary)
            {
                if (RequestDictionary.ContainsKey(requestId))
                {
                    return false;
                }
                RequestDictionary.Add(requestId, DateTime.Now);
            }
            return true;
        }

        public void AddToken(string securityToken)
        {
            lock (TokenDictionary)
            {
                if (TokenDictionary.ContainsKey(securityToken))
                {
                    return;
                }
                TokenDictionary.Add(securityToken, "Guest");
            }
        }

        public bool ValidToken(string securityToken)
        {
            bool result;
            lock (TokenDictionary)
            {
                result = TokenDictionary.ContainsKey(securityToken);
            }

            return result;
        }
    }
}
